package com.tgy.admin.Service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.tgy.admin.LoginUser;
import com.tgy.admin.Service.MenuService;
import com.tgy.admin.util.LoginUserHelp;
import com.tgy.constant.Constant;
import com.tgy.constant.RedisKey;
import com.tgy.core.service.*;
import com.tgy.pojo.SysAdminRole;
import com.tgy.pojo.SysPermission;
import com.tgy.pojo.SysRole;
import com.tgy.pojo.SysRolePermission;
import com.tgy.util.RedisUtils;
import com.tgy.vo.MenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/6/20 20:23
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private SysAdminService sysAdminService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysAdminRoleService sysAdminRoleService;
    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private SysRolePermissionService sysRolePermissionService;
    @Resource
    private RedisUtils redis;
    @Resource
    private LoginUserHelp loginUserHelp;


    @Value("${sa-token.timeout}")
    private Long outTime;

    @Override
    public void getMenuAndRoleAndPermission(String userId) {
        /*if(StrUtil.isBlank(userId)){
            GlobalException.display(GraceJSONResult.error("用户不能为空"));
        }*/
        // 根据登陆人ID查询登陆人拥有的角色ID集合
        SysAdminRole adminRole = new SysAdminRole();
        adminRole.setAid(userId);
        List<SysAdminRole> adminRoles = sysAdminRoleService.queryList(adminRole);
        if (CollectionUtil.isEmpty(adminRoles)){
            return;
        }
        List<String> roleIds = adminRoles.stream().map(SysAdminRole::getRid).collect(Collectors.toList());

        // 根据角色ID集合查询用户的菜单集合
        List<SysRole> sysRoles = sysRoleService.queryByIds(roleIds);
        // 过滤掉不用的角色
        sysRoles  = sysRoles.stream().filter(t -> t.getAvailable() == 1).collect(Collectors.toList());
        roleIds = sysRoles.stream().map(SysRole::getId).collect(Collectors.toList());
        // 添加角色缓存
        redis.set(RedisKey.LOGIN_USER_ROLE+":"+userId, JSONObject.toJSONString(sysRoles),outTime);

        // 根据角色ID集合查询权限ID集合
        List<SysRolePermission> rolePermissions = sysRolePermissionService.queryByRoleIds(roleIds);
        if (CollectionUtil.isEmpty(rolePermissions)){
            return;
        }
        List<String> perIds = rolePermissions.stream().map(SysRolePermission::getPid).collect(Collectors.toList());

        // 根据权限id集合查询（包含菜单和权限的）
        List<SysPermission> permissions = sysPermissionService.queryByIds(perIds);
        permissions.sort(Comparator.comparing(SysPermission::getSort));
        // 过滤掉不用的菜单和权限
        permissions  = permissions.stream().filter(t -> t.getAvailable() == 1).collect(Collectors.toList());
        // 根据类型分为是菜单和权限的集合
        Map<String, List<SysPermission>> cateMap = permissions.stream().collect(Collectors.groupingBy(SysPermission::getCate));

        List<SysPermission> menuList = cateMap.get(Constant.TYPE_MENU);
        List<SysPermission> permissionList = cateMap.get(Constant.TYPE_PERMISSION);

        // 添加权限缓存
        redis.set(RedisKey.LOGIN_USER_PERMISSION+":"+userId, JSONObject.toJSONString(permissionList),outTime);

        // 构造菜单
        // 获取出pid为-1的顶级菜单，按顺序排列
        List<MenuVo> menu = getMenu(menuList, Constant.TYPE_TOP);
        // 添加菜单缓存
        redis.set(RedisKey.LOGIN_USER_MENU+":"+userId, JSONObject.toJSONString(menu),outTime);
    }

    @Override
    public List<MenuVo> getMenu() {
        LoginUser loginUser = loginUserHelp.getLoginUser();
        List<MenuVo> menus = loginUser.getMenus();
        if (CollectionUtil.isEmpty(menus)){
            return new ArrayList<>();
        }
        return menus;
    }

    @Override
    public List<String> getRole() {
        LoginUser loginUser = loginUserHelp.getLoginUser();
        List<SysRole> roles = loginUser.getRoles();
        if (CollectionUtil.isEmpty(roles)){
            return new ArrayList<>();
        }
        return roles.stream().map(SysRole::getName).collect(Collectors.toList());
    }

    @Override
    public List<String> getPermission() {
        LoginUser loginUser = loginUserHelp.getLoginUser();
        List<SysPermission> permissions = loginUser.getPermissions();
        if (CollectionUtil.isEmpty(permissions)){
            return new ArrayList<>();
        }

        return permissions.stream().map(SysPermission::getPercode).collect(Collectors.toList());
    }

    private List<MenuVo> getMenu(List<SysPermission> menuList,String id){
        List<MenuVo> menuVoList = new ArrayList<>();
        List<SysPermission> list = menuList.stream().filter(t -> id.equals(t.getPid()))
                .sorted(Comparator.comparing(SysPermission::getSort)).collect(Collectors.toList());
        for (SysPermission permission : list) {
            MenuVo menuVo = new MenuVo();
            BeanUtils.copyProperties(permission,menuVo);
            List<MenuVo> list1 = getMenu(menuList,permission.getId());
            menuVo.setChildren(list1);
            menuVoList.add(menuVo);
        }
        return menuVoList;
    }
}
